package cn.waqwb.controller;

import cn.waqwb.entity.Book;
import cn.waqwb.entity.BookItem;
import cn.waqwb.entity.Cart;
import cn.waqwb.entity.CartItem;
import cn.waqwb.service.BookService;
import cn.waqwb.service.impl.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class BuyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        BookService bookService = new BookServiceImpl();
        int index = -1;
        //1.获取书籍
        String bookId = (request.getParameter("bookId"));
        Book book = bookService.getBookById(Integer.parseInt(bookId));
        //2.创建或者获取一个购物车
        HttpSession session = request.getSession();
        Map<String, CartItem> cart = (Map<String, CartItem>)session.getAttribute("cart");
        //3.将商品添加到购物车中
        if (cart != null) {
            // 从购物车获取该商品
            CartItem cartItem = cart.get(bookId);
            // 判断商品是不是第一次添加
            if (cartItem != null) {
                // 非第一次添加，数量加1
                cartItem.setAmount(cartItem.getAmount() + 1);
            } else {
                // 第一次添加，构建商品信息，并保存到购物车
                CartItem item = new CartItem();
                item.setId(book.getId());
                item.setBookName(book.getProductName());
                item.setDangPrice(book.getDangPrice());
                item.setFixedPrice(book.getFixedPrice());
                item.setAmount(1);
                cart.put(bookId, item);
            }
        } else {
            // 购物车不存在情况，先创建购物车，再添加商品到购物车
            cart = new HashMap<String, CartItem>();
            session.setAttribute("cart", cart);
            CartItem item = new CartItem();
            item.setId(book.getId());
            item.setBookName(book.getProductName());
            item.setDangPrice(book.getDangPrice());
            item.setFixedPrice(book.getFixedPrice());
            item.setAmount(1);
            cart.put(bookId, item);
        }

        // 返回结果
        PrintWriter writer = response.getWriter();
        writer.write("Success！");
    }

}
